/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pigx.user.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.customize.enums.AbnormalEnum;
import com.pig4cloud.pigx.common.customize.exception.DuckweedException;
import com.pig4cloud.pigx.common.customize.security.utils.SecurityUtil;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.user.constant.RedisMessageType;
import com.pig4cloud.pigx.user.dto.*;
import com.pig4cloud.pigx.user.entity.User;
import com.pig4cloud.pigx.user.enums.UserEnums;
import com.pig4cloud.pigx.user.mapper.UserMapper;
import com.pig4cloud.pigx.user.service.UserService;
import com.pig4cloud.pigx.user.util.StringRandom;
import com.pig4cloud.pigx.user.vo.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.RoundingMode;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 *
 *
 * @author pigx code generator
 * @date 2022-11-18 11:52:08
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/user" )
@Api(value = "user", tags = "管理")
public class UserController {

    private final  UserService userService;

	private final StringRedisTemplate stringRedisTemplate;

	private final UserMapper userMapper;

	/**
	 * 获取所有用户id
	 * @return r
	 */
	@GetMapping("/list")
	public R<List<Long>> getAdminUserList() {
		return userService.getAdminUserList();
	}

    /**
     * 管理端分页查询
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @PostMapping("/page" )
    @PreAuthorize("@pms.hasPermission('user_user_view')" )
    public R<Page<AdminUserPageVO>> getUserPage(@RequestBody AdminUserPageDTO dto) {
        return userService.getAdminPage(dto);
    }

	/**
	 * 查询直推
	 * @return r
	 */
	@GetMapping("/direct")
	public R<List<SelectUserByIdListVO>> getDirectUser() {
		// 查询用户
		PigxUser user = SecurityUtil.getLoginUser();
		if (user == null) {
			throw new DuckweedException(AbnormalEnum.MSG.OPTIONS_USER_NOT_FOUND);
		}
		return userService.getChildVoList(0,user.getId());
	}

	/**
	 * 查询间推
	 * @return r
	 */
	@GetMapping("/indirect")
	public R<List<SelectUserByIdListVO>> getIndirectUser() {
		// 查询用户
		PigxUser user = SecurityUtil.getLoginUser();
		if (user == null) {
			throw new DuckweedException(AbnormalEnum.MSG.OPTIONS_USER_NOT_FOUND);
		}
		return userService.getChildVoList(1,user.getId());
	}

	/**
	 * 查询所有子集
	 * @return r
	 */
	@GetMapping("/all/child/{id}")
	public R<List<SelectUserByIdListVO>> getAllChildByUser(@PathVariable("id" ) Long id) {
		if (id != null && id == 0) {
			PigxUser user = SecurityUtil.getLoginUser();
			if (user == null) {
				throw new DuckweedException(AbnormalEnum.MSG.OPTIONS_USER_NOT_FOUND);
			}
			return userService.getChildVoList(2,user.getId());
		}
		return userService.getChildVoList(2,id);
	}

	/**
	 * 查询单个人
	 * @param id id
	 * @return r
	 */
	@GetMapping("/child/{id}")
	public R<SelectUserByIdListVO> getOneById(@PathVariable("id" ) Long id) {
		SelectUserByIdListVO vo = userMapper.selectOneByIdList(id);
		if (vo != null && vo.getFuelQuantity() != null) {
			vo.setFuelQuantity(vo.getFuelQuantity().setScale(3, RoundingMode.DOWN).stripTrailingZeros());
			vo.setFuelBalance(vo.getFuelBalance().setScale(3, RoundingMode.DOWN).stripTrailingZeros());
			vo.setRechargeQuantity(vo.getRechargeQuantity().setScale(3, RoundingMode.DOWN).stripTrailingZeros());
		}
		return R.ok(vo == null ? new SelectUserByIdListVO() : vo);
	}

    /**
     * 通过id查询
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/detail/{id}" )
    @PreAuthorize("@pms.hasPermission('user_user_view')" )
    public R<AdminUserTreeVO> getById(@PathVariable("id" ) Long id) {
        return userService.adminGetUserDetail(id);
    }

	/**
	 * 通过id查询
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}" )
	@PreAuthorize("@pms.hasPermission('user_user_view')" )
	public R<User> getOneByUpdate(@PathVariable("id" ) Long id) {
		User user = userService.getById(id);
		user.setPassword(null);
		return R.ok(user);
	}

    /**
     * 新增
     * @param user
     * @return R
     */
    @ApiOperation(value = "新增", notes = "新增")
    @SysLog("新增" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('user_user_add')" )
    public R<String > save(@RequestBody User user) {
        return userService.adminInsert(user);
    }

    /**
     * 修改
     * @param user
     * @return R
     */
    @ApiOperation(value = "修改", notes = "修改")
    @SysLog("修改" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('user_user_edit')" )
    public R updateById(@RequestBody User user) {
        return R.ok(userService.updateById(user));
    }

	/**
	 * 删除用户
	 * @param id id
	 * @return r
	 */
	@DeleteMapping("/{id}" )
	public R deleteById(@PathVariable("id" ) Long id) {
		return R.ok(userService.removeById(id));
	}

	/**
	 * 用户注册
	 * @param dto dto
	 * @return r
	 */
	@PostMapping("/registered")
	public R<String> registered(@RequestBody RegisteredUserDTO dto) {
		return userService.registered(dto);
	}

	/**
	 * 用户产生燃油费的后续操作
	 *
	 * @return r
	 */
	@PostMapping("/transaction")
	@Async
	public CompletableFuture<R<String>> transactionThen(@RequestBody TransactionThenDTO dto) {
		userService.transactionThen(dto);
		return CompletableFuture.completedFuture(R.ok());
	}

	/**
	 * 获取用户签名字符串
	 *
	 * @return
	 */
	@Inner(value = false)
	@ApiOperation(value = "获取用户签名字符串", notes = "获取用户签名字符串，@RequestBody：address(钱包地址)")
	@PostMapping("/getAddressMassage")
	public R getAddressMassage(@RequestBody User user) {
		String massage = StringRandom.getLowercaseStringRandom(16);
		stringRedisTemplate.opsForValue().set(
				user.getAddress() + " massage = " + RedisMessageType.Customer_Address_Message,
				massage, 60 * 3, TimeUnit.SECONDS);
		return R.ok(massage);
	}

	/**
	 * 获取用户签名字符串
	 *
	 * @return
	 */
	@ApiOperation(value = "获取用户签名字符串", notes = "获取用户签名字符串，@RequestBody：address(钱包地址)")
	@PostMapping("/update/address/message")
	public R<String> getUpdateLoginAddressMessage(@RequestBody User user) {
		String massage = StringRandom.getLowercaseStringRandom(16);
		stringRedisTemplate.opsForValue().set(
				user.getAddress() + " massage = " + RedisMessageType.UPDATE_LOGIN_ADDRESS_MESSAGE,
				massage, 60 * 3, TimeUnit.SECONDS);
		return R.ok(massage);
	}

	/**
	 * 发送邮件
	 * @param dto dto
	 * @return r
	 */
	@PostMapping("/email")
	public R<String> sendRegisteredEmail(@RequestBody SendEmailDTO dto) {
		return userService.sendEmail(dto);
	}

	/**
	 * 发送邮件 不需要token
	 * @param dto dto
	 * @return r
	 */
	@Inner(value = false)
	@PostMapping("/email/l")
	public R<String> sendEmailNoToken(@RequestBody SendEmailDTO dto) {
		if (!dto.getType().equals(UserEnums.EmailType.Email_Login.getValue())) {
			return R.failed("错误的邮箱类型");
		}
		return userService.sendEmail(dto);
	}

	 /**
	 * 获取登录用户信息
	 * @return r
	 */
	 @GetMapping("/app/detail")
	 public R<AppUserDetailVO> getAppUserDetail(@RequestParam("id") Long id) {
		 return userService.getAppUserDetail(id);
	 }

	/**
	 * 密码解密后请求pigx-gateway中
	 *
	 * @param header
	 * @param userMobileDTO
	 * @return
	 */
	@Inner(value = false)
	@ApiOperation(value = "用户签名验证", notes = "用户签名验证 @RequestBody address、 Return：userIsExist（用户是否注册 false=未注册 true=已注册）、userInfo")
	@PostMapping("/login")
	public R login(@RequestHeader HttpHeaders header, @RequestBody UserMobileDTO userMobileDTO) {
		return userService.login(header, userMobileDTO);
	}

	/**
	 * 邮箱登录
	 * @param header header
	 * @param dto dto
	 * @return r
	 */
	@Inner(value = false)
	@PostMapping("/email/login")
	public R<AppUserVO> emailLogin(@RequestHeader HttpHeaders header,@RequestBody EmailLoginDTO dto) {
		return userService.emailLogin(header,dto);
	}

	/**
	 * 邮箱注册并登录
	 * @param header header
	 * @param dto dto
	 * @return r
	 */
	@Inner(value = false)
	@PostMapping("/email/registered")
	public R<AppUserVO> emailRegisteredAndLogin(HttpHeaders header,@RequestBody RegisteredUserDTO dto) {
		return userService.emailRegisteredAndLogin(header,dto);
	}


	/**
	 * 获取app用户余额
	 * @return r
	 */
	@GetMapping("/wallet")
	public R<UserBalanceVO> getUserBalance() {
		return userService.getUserBalance();
	}

	/**
	 * 修改用户资金密码
	 * @param dto dto
	 * @return r
	 */
	@PutMapping("/password")
	public R<String> updateUserPassword(@RequestBody UpdateUserPasswordDTO dto) {
		return userService.updateUserPassword(dto);
	}

	/**
	 * 修改用户邮箱
	 * @param dto dto
	 * @return r
	 */
	@PutMapping("/email")
	public R<String> updateUserEmail(@RequestBody UpdateUserEmailDTO dto) {
		return userService.updateUserEmail(dto);
	}

	/**
	 * 修改用户地址
	 * @param dto dto
	 * @param header header
	 * @return r
	 */
	@PutMapping("/address")
	public R<String> updateLoginAddress(@RequestHeader HttpHeaders header,@RequestBody UpdateLoginAddressDTO dto) {
		return userService.updateLoginAddress(header,dto);
	}

	/**
	 * 游客token
	 * @param header header
	 * @return r
	 */
	@Inner(value = false)
	@GetMapping("/tourist")
	public R<String> getTouristToken(@RequestHeader HttpHeaders header) {
		return userService.getTouristToken(header);
	}

}
